#!/bin/bash

echo "=== 应急安装模式（低内存服务器）==="

# 检查内存
echo "当前内存状况："
free -m

# 创建临时swap
echo "创建临时swap文件..."
sudo dd if=/dev/zero of=/tmp/swapfile bs=1M count=1024
sudo chmod 600 /tmp/swapfile
sudo mkswap /tmp/swapfile
sudo swapon /tmp/swapfile

# 使用最小依赖包
echo "使用最小依赖包安装..."
cp package-minimal.json package.json

# 设置npm内存限制
export NODE_OPTIONS="--max-old-space-size=512"

# 清理并重新安装
rm -rf node_modules package-lock.json

# 使用yarn替代npm（内存占用更小）
if ! command -v yarn &> /dev/null; then
    echo "安装yarn..."
    npm install -g yarn --registry=https://registry.npmmirror.com
fi

echo "使用yarn安装依赖..."
yarn install --registry=https://registry.npmmirror.com --network-timeout 300000

# 如果yarn也失败，使用逐个安装
if [ $? -ne 0 ]; then
    echo "yarn失败，尝试逐个安装核心依赖..."
    npm install next@14.0.4 --registry=https://registry.npmmirror.com --no-optional
    npm install react@18.2.0 react-dom@18.2.0 --registry=https://registry.npmmirror.com --no-optional
    npm install sqlite3@5.1.7 --registry=https://registry.npmmirror.com --no-optional
    npm install express@4.18.2 --registry=https://registry.npmmirror.com --no-optional
    npm install tailwindcss@3.3.6 --registry=https://registry.npmmirror.com --no-optional
fi

# 创建目录
mkdir -p data uploads

# 初始化数据库
node scripts/init-db.js

echo "应急安装完成！"
echo "清理临时swap..."
sudo swapoff /tmp/swapfile
sudo rm -f /tmp/swapfile

echo "尝试构建..."
npm run build